<?php
declare (strict_types=1);

namespace app\common\service;

use app\common\model\AdminVisitLogModel;
use think\facade\Cache;

//系统配置
class AdminVisitLogService
{
    /*
     * @title 记录日志
     * @description 每一个用户每一分钟只记录一次
     * @param string $key
     * @return string
     * */
    public function recordLog(int $uid): bool
    {
        $now = date('Y-m-d H:i:s');
        $date = substr($now, 0, 10);

        $key = 'record_log:' . $date . (string)$uid;
        $last_visit_time = Cache::store('redis')->get($key);
        if (empty($last_visit_time)) {
            $last_visit_time = AdminVisitLogModel::where('date', $date)
                ->where('uid', '=', $uid)
                ->value('last_visit_time');
        }
        if (empty($last_visit_time)) { //为空表示今天首次访问-添加
            AdminVisitLogModel::create([
                'date' => $date,
                'uid' => $uid,
                'ip' => request()->ip(),
                'last_ip' => request()->ip(),
                'visit_time' => $now,
                'last_visit_time' => $now,
            ]);
        } else {
            //每1分钟记录一次
            if (abs(time() - strtotime($last_visit_time)) > 60) {
                AdminVisitLogModel::update([
                    'last_ip' => request()->ip(),
                    'last_visit_time' => $now,
                ], [
                    'date' => $date,
                    'uid' => $uid,
                ]);
            }
        }

        return true;
    }


}
